package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.swing.*;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    RestHighLevelClient client;
    @Autowired
    IHotelService hotelService;

    @Override
    public PageResult search(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            buildBasicQuery(params, request);
            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("发生了{}错误", e.getMessage());
        }
        return null;
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            buildBasicQuery(params, request);
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //获取
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2.根据品牌名称，获取品牌结果
            List<String> cityList = getAggByName(aggregations, "cityAgg");
            result.put("city", cityList);
            // 4.3.根据品牌名称，获取品牌结果
            List<String> starList = getAggByName(aggregations, "starAgg");
            result.put("starName", starList);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void insert(Long hotelId) {
        try {
            // 0.根据id查询酒店数据
            Hotel hotel = hotelService.getById(hotelId);

            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Long hotelId) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", String.valueOf(hotelId));
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg").field("brand").size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg").field("city").size(100));
        request.source().aggregation(AggregationBuilders
                .terms("starAgg").field("starName").size(100));
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根据聚合名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isNoneBlank(key)) {     //不为空
            boolQuery.must(QueryBuilders.matchQuery("all", key));
            request.source().query(QueryBuilders.matchQuery("all", key));
            //高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        } else {//todo 为空
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //城市
        if (StringUtils.isNoneBlank(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        //品牌
        if (StringUtils.isNoneBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //星级
        if (StringUtils.isNoneBlank(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //价格
        if (params.getMaxPrice() != null && params.getMinPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));
        }

        // 2.2.分页
        int page = params.getPage();
        int size = params.getSize();
        request.source().from((page - 1) * size).size(size);

        //位置排序
        if (StringUtils.isNoneBlank(params.getLocation())) {
            request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }
        if (params.getSortBy().equalsIgnoreCase("default")) {
            // 2.算分控制
            FunctionScoreQueryBuilder functionScoreQuery =
                    QueryBuilders.functionScoreQuery(
                            // 原始查询，相关性算分的查询
                            boolQuery,
                            // function score的数组
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                    // 其中的一个function score 元素
                                    new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                            // 过滤条件
                                            QueryBuilders.termQuery("isAD", true),
                                            // 算分函数
                                            ScoreFunctionBuilders.weightFactorFunction(5)
                                    )
                            });
            request.source().query(functionScoreQuery);
        }

        if (params.getSortBy().equalsIgnoreCase("score")) {
            request.source().sort("score", SortOrder.DESC);
            request.source().query(boolQuery);
        }
        if (params.getSortBy().equalsIgnoreCase("price")) {
            request.source().sort("price", SortOrder.ASC);
            request.source().query(boolQuery);
        }

//        request.source().query(boolQuery);

    }

    private PageResult handleResponse(SearchResponse response) throws IOException {

        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            hotels.add(hotelDoc);

            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    System.out.println(name);
                    // 覆盖非高亮结果
                    hotelDoc.setName(name);
                }
            }

        }
        return new PageResult(total, hotels);
    }

//    @Override
//    public PageResult search(RequestParams params) {
//        try {
//            // 1.准备Request
//            SearchRequest request = new SearchRequest("hotel");
//            // 2.准备DSL
//            // 2.1.query
//            String key = params.getKey();
//            if (key == null || "".equals(key)) {
//                request.source().query(QueryBuilders.matchAllQuery());
//            } else {
//                request.source().query(QueryBuilders.matchQuery("all", key));
//            }
//
//            // 2.2.分页
//            int page = params.getPage();
//            int size = params.getSize();
//            request.source().from((page - 1) * size).size(size);
//
//            // 3.发送请求
//            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//            // 4.解析响应
//            return handleResponse(response);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//    // 结果解析
//    private PageResult handleResponse(SearchResponse response) {
//        // 4.解析响应
//        SearchHits searchHits = response.getHits();
//        // 4.1.获取总条数
//        long total = searchHits.getTotalHits().value;
//        // 4.2.文档数组
//        SearchHit[] hits = searchHits.getHits();
//        // 4.3.遍历
//        List<HotelDoc> hotels = new ArrayList<>();
//        for (SearchHit hit : hits) {
//            // 获取文档source
//            String json = hit.getSourceAsString();
//            // 反序列化
//            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
//            // 放入集合
//            hotels.add(hotelDoc);
//        }
//        // 4.4.封装返回
//        return new PageResult(total, hotels);
//    }


}
